<script setup lang="ts">
import { nextTick, onMounted, ref } from 'vue'
import { ElMessage } from 'element-plus'
import {
  reqPermissionRoleDoAssign,
  reqPermissionRoleToAssign,
} from '@/api/acl/permission'
import type { Role } from '@/api/acl/role/type.ts'
import type {
  DoAssignPermissionData,
  Permission,
} from '@/api/acl/permission/type.ts'

const $emit = defineEmits(['get-role-list'])

const show = ref<boolean>(false)

const roleParams: any = {
  roleId: '',
  roleName: '',
}

const permissionList = ref<Permission[]>([])
const selectedPermissionIdList = ref<number[]>([])

const permissionProps = {
  label: 'name',
  children: 'children',
}

const treeRef = ref<any>()
const drawerRef = ref<any>()

const filterSelectedPermissionIdList = (
  permissionList: Permission[],
  selectedList: number[] = [],
) => {
  permissionList.forEach((permission) => {
    if (permission.children && permission.children.length > 0) {
      filterSelectedPermissionIdList(permission.children, selectedList)
    }
    if (permission?.select && permission?.level == 4) {
      selectedList.push(permission?.id as number)
    }
  })
  return selectedList
}

const getPermissionList = async (roleId: number) => {
  try {
    const { code, data, message } = await reqPermissionRoleToAssign(roleId)
    if (code == 200) {
      permissionList.value = data
      selectedPermissionIdList.value = filterSelectedPermissionIdList(
        permissionList.value,
        [],
      )
    } else {
      ElMessage.error(message)
    }
  } catch (e: any) {
    ElMessage.error(e?.message)
  }
}

const initPermission = (role: Role) => {
  resetRoleData()
  Object.assign(roleParams, role)
  getPermissionList(roleParams?.id)
  show.value = true

  nextTick(() => {
    // 滚动到最顶部
    drawerRef.value.$refs.drawerRef.querySelector(
      '.el-drawer__body',
    ).scrollTop = 0
  })
}

const resetRoleData = () => {
  Object.assign(roleParams, {
    roleId: '',
    roleName: '',
  })
  selectedPermissionIdList.value = []
}

const onConfirm = async () => {
  const doAssignPermissionData: DoAssignPermissionData = {
    roleId: roleParams.id as number,
    permissionIdList: [],
  }
  const arr = treeRef.value.getCheckedKeys(false)
  const arr1 = treeRef.value.getHalfCheckedKeys()
  doAssignPermissionData.permissionIdList = arr.concat(arr1)
  try {
    const { code, message } = await reqPermissionRoleDoAssign(
      doAssignPermissionData,
    )
    if (code == 200) {
      ElMessage.success('分配权限成功')
      // 如果修改了登录用户所拥有的角色，那么重新刷新页面
      window.location.reload()
      // $emit('get-role-list')
      // show.value = false
    } else {
      ElMessage.error(message)
    }
  } catch (e: any) {
    ElMessage.error(e?.message)
  }
}

const onCancel = () => {
  show.value = false
}

onMounted(() => {})
defineExpose({
  initPermission,
})
</script>

<template>
  <el-drawer v-model="show" ref="drawerRef">
    <template #header>
      <h4>分配权限：{{ roleParams?.roleName }}</h4>
    </template>
    <template #default>
      <el-tree
        :data="permissionList"
        :props="permissionProps"
        :default-checked-keys="selectedPermissionIdList"
        node-key="id"
        default-expand-all
        show-checkbox
        empty-text="加载中..."
        ref="treeRef"
      ></el-tree>
    </template>
    <template #footer>
      <el-button type="primary" @click="onConfirm">确认</el-button>
      <el-button @click="onCancel">取消</el-button>
    </template>
  </el-drawer>
</template>

<style scoped lang="scss"></style>
